package com.example.testnetty.nettyserver;

import android.content.Context;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelId;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;


public class NettyServer {

    public static void initStart(int port, final Context context) {
        ServerBootstrap bootstrap = new ServerBootstrap();
        EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();

        try {
            bootstrap.group(boss, worker);

            bootstrap.channel(NioServerSocketChannel.class);

            bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    // 超时，  写超时 ，  读写超时 :  单位 秒 （剔除长时间不用的连接,减少服务器的压力）
                    socketChannel.pipeline().addLast(new IdleStateHandler(30, 30, 60));
                    //判断是否有 \n 或 \r\n，如果有，就作为结束位置
                    // socketChannel.pipeline().addLast(new LineBasedFrameDecoder(2048));
//                    socketChannel.pipeline().addLast(new StringDecoder(Charset.forName("UTF-8")));
                    socketChannel.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8));
                    socketChannel.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8));
//                    socketChannel.pipeline().addLast(new StringEncoder(Charset.forName("UTF-8")));

                    socketChannel.pipeline().addLast(new ServerChannel(context));
                }
            });
            //设置缓冲池大小
            bootstrap.option(ChannelOption.SO_BACKLOG, 2048);
            //保持长连接
            bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
            //关闭延迟发送
            bootstrap.childOption(ChannelOption.TCP_NODELAY, true);

            ChannelFuture future = bootstrap.bind(port);

            future.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

    //与客户端约定发送数据类型  事实结果
    public static void sendIfltekSuccess(String words) {
        String str = "{\"cmd\":\"0\",\"action\":\"words\",\"command\":\"sendWords\",\"time\":" + System.currentTimeMillis() + "\",\"data\":\"" + words + "\"}";
        ChannelGroups.broadcast(Unpooled.copiedBuffer(str.getBytes()));
    }

    public static void sendIfltekError() {
        String str = "{\"cmd\":\"-1\",\"action\":\"words\",\"command\":\"sendError\",\"time\":" + System.currentTimeMillis() + "\",\"data\":\"讯飞数据异常\"}";
        ChannelGroups.broadcast(Unpooled.copiedBuffer(str.getBytes()));
    }


    public static void sendOne(ChannelId channelid, String json) {
        if (channelid != null)
            ChannelGroups.SendSpecifyClient(channelid, Unpooled.copiedBuffer(json.getBytes()));
    }


    public static void sendOne(String host, String json) {
        ChannelId channelId = ChannelMap.find(host);
        if (channelId != null) {
            ChannelGroups.SendSpecifyClient(channelId, Unpooled.copiedBuffer(json.getBytes()));
        }
    }

}

//    public static ByteBuffer SendRoot(String data) {
//        String head = "UAID"; //包头    55434F4D  固定不变
//        String tail = "UOFF";  //包尾   55454F46  固定不变
//        String length = "";
//
//        LogUtil.E("Json数据: " + data);
//        //去除多余的空格。
//        byte[] dataBody = data.replace(" ", "").trim().getBytes(Charset.defaultCharset());
//        byte[] dataHead = head.getBytes(Charset.defaultCharset());
//        byte[] dataTail = tail.getBytes(Charset.defaultCharset());
//        ByteBuffer buffer = ByteBuffer.allocate(dataHead.length + 4 + dataBody.length + dataTail.length);
//        buffer.order(ByteOrder.BIG_ENDIAN);
//        buffer.put(dataHead);
//
//
//        if (dataBody.length < 1000 && dataBody.length >= 100) {
//            length = "0" + dataBody.length;
//        } else if (dataBody.length >= 10 && dataBody.length < 100) {
//            length = "00" + dataBody.length;
//        } else if (dataBody.length > 0 && dataBody.length < 10) {
//            length = "000" + dataBody.length;
//        }
//        buffer.put(length.getBytes());
//        buffer.put(dataBody);
//        buffer.put(dataTail);
//
//        return buffer;
//
//    }

